package com.zhu.es.utils;


import com.zhu.es.pojo.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

//爬取京东网页数据
@Component
public class HtmlParseUtil {

    public static void main(String[] args) throws IOException {
        new HtmlParseUtil().parseJD("java").forEach(System.out::println);
    }

    public List<Content> parseJD(String keywords) throws IOException{
        //获取请求
        String url = "https://search.jd.com/Search?keyword="+keywords;
        //解析网页
        Document document = Jsoup.parse(new URL(url), 30000);
        Element element = document.getElementById("J_goodsList");
        //获取所有li元素
        Elements elements = element.getElementsByTag("li");

        //list保存获取的数据
        ArrayList<Content> goodList = new ArrayList<>();

        //获取元素中的内容，这里的el，就是每个li标签了
        for (Element el : elements) {
            //去除数据为空的
            if(!el.attr("class").equalsIgnoreCase("ps-item")){
                //关于图片，很多网站图片都是使用懒加载
                String img = el.getElementsByTag("img").eq(0).attr("src");
                String price = el.getElementsByClass("p-price").eq(0).text();
                String title = el.getElementsByClass("p-name").eq(0).text();

                //把获取的数据封装成对象
                Content content = new Content();
                content.setImg(img);
                content.setPrice(price);
                content.setTitle(title);
                goodList.add(content);
            }
        }
        return goodList;
    }
}
